package com.zhika.zishi.activity;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zhika.zishi.MyApplication;
import com.zhika.zishi.constant.InternetConstant;
import com.zhika.zishi.db.OperateDb;
import com.zhika.zishi.fragments.set.AboutUsFragment;
import com.zhika.zishi.fragments.set.ModifyPasswordFragment;
import com.zhika.zishi.fragments.set.MyselfSettingFragment;
import com.zhika.zishi.fragments.set.SaidUsFragment;
import com.zhika.zishi.fragments.set.SecureRemindFragment;
import com.zhika.zishi.fragments.set.SettingFragment;
import com.zhika.zishi.util.ActivityCollector;
import com.zhika.zishi.util.LogUtil;

import org.apache.http.Header;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import org.json.JSONStringer;

/**
 * Created by shi-02 on 2015/5/6.
 * 有关设置的activity
 */
public class SettingActivity extends BaseFragmentActivity implements
        SettingFragment.OnSettingInterfer, MyselfSettingFragment.OnMyselfSettingInterface,
        SecureRemindFragment.OnSecureRemindInterface, SaidUsFragment.OnSaidUsInterface,
        AboutUsFragment.OnAboutUsInterface, ModifyPasswordFragment.OnModifyPasswordInterface {


    private static final String TAG = "SettingActivity";

    //操作数据库的对象
    private OperateDb operateDb;

    //设置
    private SettingFragment settingFragment;

    //个人资料设置
    private MyselfSettingFragment myselfSettingFragment;

    //隐私与安全，提醒与通知
    private SecureRemindFragment secureRemindFragment;

    //吐槽我们
    private SaidUsFragment saidUsFragment;

    //关于我们
    private AboutUsFragment aboutUsFragment;

    //修改密码
    private ModifyPasswordFragment modifyPasswordFragment;

    //handler--修改密码
    private static final int MODIFY_PASSWORD_HANDLER = 1;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MODIFY_PASSWORD_HANDLER:

                    //修改成功
                    if (msg.arg1 == 1) {
                        //2 代表该用户已退出
                        operateDb.updateIsLoginState(MyApplication.userId, 2);
                        Intent intent = new Intent(SettingActivity.this, MainActivity.class);
                        intent.putExtra("intent", "login");
                        startActivity(intent);
                        ActivityCollector.finishAllActivity();
                    }
                    //修改失败
                    else {
                        String errorStr = (String) msg.obj;
                        MyApplication.showToast("修改密码失败:" + errorStr);
                    }
                    break;
            }
        }
    };

    @Override
    public Fragment createFragment() {
        if (settingFragment == null) {
            settingFragment = new SettingFragment();
        }

        return settingFragment;
    }

    @Override
    public void doThing() {

        //实例化操作数据库的对象
        operateDb = new OperateDb(SettingActivity.this);
    }

    @Override
    public void finishActivity() {
        finish();
    }

    @Override
    public void settingMyselfInfo() {
        if (myselfSettingFragment == null) {
            myselfSettingFragment = new MyselfSettingFragment();
        }
        startFragment(settingFragment, myselfSettingFragment);
    }

    @Override
    public void secureRemind(String type) {
        if (secureRemindFragment == null) {
            secureRemindFragment = new SecureRemindFragment();
        }
        Bundle bundle = new Bundle();
        bundle.putString("secure_remind", type);
        secureRemindFragment.setArguments(bundle);
        startFragment(settingFragment, secureRemindFragment);
    }

    @Override
    public void saidUs() {

        if (saidUsFragment == null) {
            saidUsFragment = new SaidUsFragment();
        }

        startFragment(settingFragment, saidUsFragment);

    }

    @Override
    public void aboutUs() {

        if (aboutUsFragment == null) {
            aboutUsFragment = new AboutUsFragment();
        }

        startFragment(settingFragment, aboutUsFragment);
    }

    @Override
    public void remoteMyselfFragment() {
        onBackPressed();
    }

    @Override
    public void remoteSecureRemindFragment() {
        onBackPressed();
    }

    @Override
    public void modifyPassword() {
        if (modifyPasswordFragment == null) {
            modifyPasswordFragment = new ModifyPasswordFragment();
        }

        startFragment(secureRemindFragment, modifyPasswordFragment);
    }

    @Override
    public void remoteSaidUsFragment() {
        onBackPressed();
    }

    @Override
    public void remoteAboutUsFragment() {
        onBackPressed();
    }

    @Override
    public void remoteModifyPasswordFragment() {
        onBackPressed();
    }

    @Override
    public void sureModifyPassword(String oldPassword, String newPassword) {
        String url = InternetConstant.SERVER_ADDRESS + InternetConstant.MODIFY_PASSWORD +
                "?uid=" + MyApplication.userId + "&token=" + MyApplication.token + "&deviceTag=" + MyApplication.device_id;
        LogUtil.e(TAG, "修改密码-url:" + url);

        //url params uid= token= deviceTag= { “oldpasswd”:”zs1234”, “passwd”:”zs12345” }
        try {
            JSONStringer stringer = new JSONStringer().object()
                    .key("oldpasswd").value(oldPassword)
                    .key("passwd").value(newPassword)
                    .endObject();
            LogUtil.e(TAG, "修改密码--请求参数：" + stringer.toString());

            StringEntity entity = new StringEntity(stringer.toString(), HTTP.UTF_8);

            MyApplication.asyncHttpClient.post(SettingActivity.this, url, entity, InternetConstant.CONTENT_TYPE, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int i, Header[] headers, byte[] bytes) {
                    String jsonData = new String(bytes);
                    LogUtil.e(TAG, "修改密码--成功码：code=" + i + ";返回的数据：" + jsonData);
                    parseModifyPasswordJson(jsonData);
                }

                @Override
                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                    LogUtil.e(TAG, "修改密码--错误码：code=" + i);
                    throwable.printStackTrace();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析修改密码返回的数据
     *
     * @param jsonData
     */
    private void parseModifyPasswordJson(String jsonData) {

        try {
            JSONObject jsonObject = new JSONObject(jsonData);
            boolean isSuccess = jsonObject.getBoolean("success");
            Message message = Message.obtain();
            message.what = MODIFY_PASSWORD_HANDLER;

            //如果修改成功
            if (isSuccess) {
                message.arg1 = 1;
            }
            //如果修改失败
            else {
                message.arg1 = 2;
                String errorStr = jsonObject.getString("error");
                message.obj = errorStr;
            }
            handler.sendMessage(message);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
